package com.itsenpupulai.longlivetest;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.icu.text.LocaleDisplayNames;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import de.tavendo.autobahn.WebSocketConnection;
import de.tavendo.autobahn.WebSocketException;
import de.tavendo.autobahn.WebSocketHandler;
import de.tavendo.autobahn.WebSocketOptions;

public class WebSocketService extends Service {
    private static final String TAG = WebSocketService.class.getSimpleName();

    public static final String WEBSOCKET_ACTION = "WEBSOCKET_ACTION";

    private BroadcastReceiver connectionRecevier;
    private static boolean isClosed = true;
    private static WebSocketConnection webSocketConnection;
    private static WebSocketOptions options = new WebSocketOptions();
    private static boolean isExitApp = false;
    private static String websocketHost = "ws://120.25.158.1:2347";



    public WebSocketService() {
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (connectionRecevier == null){
            connectionRecevier = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
                    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

                    if (networkInfo == null || !networkInfo.isAvailable()){
                        Toast.makeText(getApplicationContext(), "网络已断开，请重新连接", Toast.LENGTH_SHORT).show();
                    }else{
                        if (webSocketConnection != null){
                            webSocketConnection.disconnect();
                        }
                        if (isClosed){

                        }
                    }

                }
            };

            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            registerReceiver(connectionRecevier, intentFilter);

        }




        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }


    public static void closeWebsocket(boolean exitApp){
        isExitApp = exitApp;
        if (webSocketConnection != null && webSocketConnection.isConnected()){
            webSocketConnection.disconnect();
            webSocketConnection = null;
        }
    }

    public static void webScoketConnect(){
        webSocketConnection = new WebSocketConnection();
        try {
            webSocketConnection.connect(websocketHost, new WebSocketHandler(){

                //websocket启动时回调
                @Override
                public void onOpen() {
                    isClosed = false;
                }
                //接收到消息时的回调
                @Override
                public void onTextMessage(String payload) {
//                    super.onTextMessage(payload);
                    Log.e(TAG, "payLoad = " + payload);
                    if (payload != null){
                        try {
                            JSONObject object = new JSONObject(payload);
                            String action = object.getString("action");
                            int code = object.getJSONObject("data").getInt("code");
                            String content = object.getJSONObject("data").getString("message");
                            Log.e(TAG, "action: " + action
                                    + "code: "  +  code
                                    + "content: " + content);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                }
                //websocket关闭时回调
                @Override
                public void onClose(int code, String reason) {
//                    super.onClose(code, reason);

                    isClosed = true;
                    Log.e(TAG, "code = " + code + "reason = " + reason);


                }
            });





        }catch (WebSocketException e){
            e.printStackTrace();
        }
    }

    public static void sendMsg(String s){
        Log.e(TAG, "sendMsg = " + s);
        if (!TextUtils.isEmpty(s)){
            if (webSocketConnection != null){
                webSocketConnection.sendTextMessage(s);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (connectionRecevier != null){
            unregisterReceiver(connectionRecevier);
        }
    }
}
